<template>
  <div style="padding:20px">
    <el-row :gutter="12">
      <el-col :span="12">
        <el-card class="kb-detail-card" shadow="never"  style="height:600px;overflow-y: auto;">
          <h2>{{ knowledgeBase.name }}</h2> 
          <!-- <p>{{ knowledgeBase.description }}</p> -->
          <el-alert :title="knowledgeBase.description" type="info" :closable="false" />
          <p><strong>向量化模型:</strong> {{ knowledgeBase.model }}</p>
          <el-upload :action="`${apiUrl}/upload`" :headers="uploadHeaders"
            :data="{ knowledge_base_id: $route.params.id }" :on-success="handleUploadSuccess"
            :before-upload="beforeUpload" multiple :on-exceed="handleExceed" style="margin-top: 20px;">
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">只能上传txt/pdf/docx文件，且不超过50MB</div>
            </template>
          </el-upload>
          <div v-if="documents.length === 0" style="text-align: center;">
            <i class="el-icon-document-empty" style="font-size: 50px;"></i>
            <el-empty description="暂无文档"></el-empty>
          </div>
          <div v-else style="width: 100%;">

            <el-table :data="documents" style="width: 100%;" max-height="400">
              <el-table-column prop="id" label="id" width="50" />
              <el-table-column prop="name" label="文件名" />
              <el-table-column prop="" label="text" width="80">
                <template #default="scope">
                  <el-button link type="primary" size="small" @click.prevent="deleteDocument(scope.row.id)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <!-- <el-row :gutter="20">
          <el-col :span="6" v-for="doc in documents" :key="doc.id">
            <el-card shadow="hover">
              <h3>{{ doc.name }}</h3>
              <div style="margin-top: 10px;">
                <el-button type="text" size="small" @click.stop="deleteDocument(doc.id)">删除</el-button>
              </div>
            </el-card>
          </el-col>
        </el-row> -->
        </el-card></el-col>
      <el-col :span="12">
        <el-card class="kb-detail-card" shadow="never" style="height:600px">
          <h3>知识片段</h3>
          <div style="background-color: #fff;border-radius: 4px;">
            <div v-if="fragments.length === 0" style="text-align: center;">
              <i class="el-icon-document-empty" style="font-size: 50px;"></i>
              <el-empty description="暂无知识片段"></el-empty>
            </div>
            <div v-else>
              <el-table :data="fragments" style="width: 100%;" max-height="800">
                <el-table-column prop="id" label="id" width="50" />
                <el-table-column prop="text" label="知识" show-overflow-tooltip />
                <el-table-column prop="" label="text" width="80">
                  <template #default="scope">
                    <el-button link type="primary" size="small" @click.prevent="deleteFragment(scope.row.id)">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <!-- <div v-for="fragment in fragments" :key="fragment.id">
          <div shadow="hover">
            <p>{{ fragment.text }}</p>
            <div style="margin-top: 10px;">
              <el-button type="text" size="small" @click.stop="deleteFragment(fragment.id)">删除</el-button>
            </div>
          </div>
        </div> -->
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus';

export default {
  data() {
    return {
      knowledgeBase: {},
      documents: [],
      fragments: [],
      apiUrl: import.meta.env.VITE_API_URL,
    };
  },
  computed: {
    uploadHeaders() {
      return {
        'Authorization': `Bearer ${localStorage.getItem('access_token')}`
      };
    }
  },
  methods: {
    async fetchKnowledgeBase() {
      try {
        const response = await fetch(`${import.meta.env.VITE_API_URL}/knowledgeBases/${this.$route.params.id}`, {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('access_token')}`
          }
        });
        if (response.status === 401) {
          localStorage.removeItem('access_token');
          this.$router.push('/login');
          return;
        }
        let data = await response.json();
        data = data.data
        this.knowledgeBase = data;
      } catch (error) {
        console.error(error);
      }
    },
    async fetchDocuments() {
      try {
        const response = await fetch(`${import.meta.env.VITE_API_URL}/knowledgeBases/documents/${this.$route.params.id}`, {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('access_token')}`
          }
        });
        if (response.status === 401) {
          localStorage.removeItem('access_token');
          this.$router.push('/login');
          return;
        }
        let data = await response.json();
        data = data.data
        this.documents = data;
      } catch (error) {
        console.error(error);
      }
    },
    async fetchFragments() {
      try {
        // Assuming we have an API endpoint to fetch fragments
        const response = await fetch(`${import.meta.env.VITE_API_URL}/knowledgeBases/fragments/${this.$route.params.id}`, {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('access_token')}`
          }
        });
        if (response.status === 401) {
          localStorage.removeItem('access_token');
          this.$router.push('/login');
          return;
        }
        let data = await response.json();
        data = data.data
        this.fragments = data;
      } catch (error) {
        console.error(error);
      }
    },
    handleUploadSuccess(response, file, fileList) {
      ElMessage.success(`${file.name} 上传成功`);
      this.fetchDocuments(); // Refresh documents list
      this.fetchFragments(); // Refresh fragments list
    },
    beforeUpload(file) {
      const isAllowedType = ['text/plain', 'application/pdf', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'image/jpeg', 'image/png'].includes(file.type);
      const isLt5M = file.size / 1024 / 1024 < 150;

      if (!isAllowedType) {
        ElMessage.error('只能上传 txt/pdf/docx/jpg/png 格式的文件!');
      }
      if (!isLt5M) {
        ElMessage.error('上传文件大小不能超过 5MB!');
      }
      return isAllowedType && isLt5M;
    },
    handleExceed(files, fileList) {
      ElMessage.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    async deleteDocument(id) {
      try {
        const response = await fetch(`${import.meta.env.VITE_API_URL}/knowledgeBases/documents/${id}`, {
          method: 'DELETE',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('access_token')}`
          }
        });
        if (response.status === 401) {
          localStorage.removeItem('access_token');
          this.$router.push('/login');
          return;
        }
        const data = await response.json();
        if (response.ok) {
          ElMessage.success(data.msg);
          this.fetchDocuments(); // Refresh documents list
          this.fetchFragments(); // Refresh fragments list
        } else {
          ElMessage.error(data.msg);
        }
      } catch (error) {
        console.error(error);
      }
    },
    async deleteFragment(id) {
      try {
        const response = await fetch(`${import.meta.env.VITE_API_URL}/knowledgeBases/fragments/${id}`, {
          method: 'DELETE',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('access_token')}`
          }
        });
        if (response.status === 401) {
          localStorage.removeItem('access_token');
          this.$router.push('/login');
          return;
        }
        const data = await response.json();
        if (response.ok) {
          ElMessage.success(data.msg);
          this.fetchFragments(); // Refresh fragments list
        } else {
          ElMessage.error(data.msg);
        }
      } catch (error) {
        console.error(error);
      }
    }
  },
  mounted() {
    this.fetchKnowledgeBase();
    this.fetchDocuments();
    this.fetchFragments();
  }
};
</script>

<style scoped>
.kb-detail-card {
  width: 100%;
  text-align: left;
}


.el-card {
  margin-bottom: 20px;
}
</style>